const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: '+08:00',
  logging: false
});

async function seedInventoryProducts() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 定义产品数据
    const products = [
      {
        sku: "SKU001",
        name: "高性能计算服务器",
        specification: "Intel Xeon E5-2680, 64GB RAM, 2TB SSD",
        stock: 15,
        minStock: 5,
        unit: "台",
        salePrice: 15000.00,
        costPrice: 12000.00,
        status: "active"
      },
      {
        sku: "SKU002",
        name: "企业级存储阵列",
        specification: "24盘位, 128GB缓存, 支持RAID 6",
        stock: 8,
        minStock: 3,
        unit: "台",
        salePrice: 8000.00,
        costPrice: 6500.00,
        status: "active"
      },
      {
        sku: "SKU003",
        name: "无线路由器",
        specification: "Wi-Fi 6, 4x4 MU-MIMO, 1.7Gbps",
        stock: 45,
        minStock: 10,
        unit: "台",
        salePrice: 800.00,
        costPrice: 500.00,
        status: "active"
      },
      {
        sku: "SKU004",
        name: "机械键盘",
        specification: "87键, 青轴, RGB背光",
        stock: 32,
        minStock: 15,
        unit: "个",
        salePrice: 350.00,
        costPrice: 200.00,
        status: "active"
      },
      {
        sku: "SKU005",
        name: "高清显示器",
        specification: "27英寸, 4K分辨率, 60Hz",
        stock: 12,
        minStock: 5,
        unit: "台",
        salePrice: 2500.00,
        costPrice: 1800.00,
        status: "active"
      },
      {
        sku: "SKU006",
        name: "移动固态硬盘",
        specification: "1TB, USB 3.2, 读取速度500MB/s",
        stock: 28,
        minStock: 10,
        unit: "个",
        salePrice: 600.00,
        costPrice: 400.00,
        status: "active"
      },
      {
        sku: "SKU007",
        name: "蓝牙耳机",
        specification: "主动降噪, 30小时续航, 触控操作",
        stock: 55,
        minStock: 20,
        unit: "副",
        salePrice: 299.00,
        costPrice: 180.00,
        status: "active"
      },
      {
        sku: "SKU008",
        name: "网络交换机",
        specification: "24口千兆, 支持VLAN, 网管型",
        stock: 6,
        minStock: 3,
        unit: "台",
        salePrice: 1200.00,
        costPrice: 800.00,
        status: "active"
      }
    ];
    
    // 插入数据到数据库
    console.log('正在插入产品数据...');
    for (const product of products) {
      // 添加组织ID（默认为1）
      const productWithOrg = {
        ...product,
        organizationId: 1
      };
      
      // 使用UPSERT操作，避免重复插入
      const [result, created] = await sequelize.query(
        `INSERT INTO products (organization_id, sku, name, specification, unit, stock, min_stock, sale_price, cost_price, status, created_at, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
         ON DUPLICATE KEY UPDATE
         name = VALUES(name),
         specification = VALUES(specification),
         unit = VALUES(unit),
         stock = VALUES(stock),
         min_stock = VALUES(min_stock),
         sale_price = VALUES(sale_price),
         cost_price = VALUES(cost_price),
         status = VALUES(status),
         updated_at = NOW()`,
        {
          replacements: [
            productWithOrg.organizationId,
            productWithOrg.sku,
            productWithOrg.name,
            productWithOrg.specification,
            productWithOrg.unit,
            productWithOrg.stock,
            productWithOrg.minStock,
            productWithOrg.salePrice,
            productWithOrg.costPrice,
            productWithOrg.status
          ]
        }
      );
      
      console.log(`产品 ${product.sku} - ${product.name} ${created ? '已插入' : '已更新'}`);
    }
    
    console.log('产品数据插入完成');
    
    // 验证插入的数据
    const [countResult] = await sequelize.query('SELECT COUNT(*) as count FROM products');
    console.log(`当前产品表总记录数: ${countResult[0].count}`);
    
    await sequelize.close();
  } catch (error) {
    console.error('操作失败:', error.message);
    if (error.stack) {
      console.error('错误堆栈:', error.stack);
    }
  }
}

// 执行脚本
seedInventoryProducts();